package com.game.gateway.start;

import java.net.InetSocketAddress;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.game.common.Transmitter;
import com.game.common.config.BaseServerConfig;
import com.game.core.net.server.SimpleCSNettyInitializer;
import com.game.core.net.server.SimpleClient;
import com.game.core.net.server.SimpleSSNettyInitializer;
import com.game.core.net.server.SimpleServer;
import com.game.core.service.ServiceContainer;
import com.game.core.session.SessionService;
import com.game.gateway.service.server.ServerService;
import com.game.message.proto.server.ServerProtoBuf.BattleInfoPROTO;

public class NetInitializer
{
	private Logger logger = LoggerFactory.getLogger(NetInitializer.class);

	private SSMessageInitializer ssMsgInitializer;
	private SimpleSSNettyInitializer ssInitializer;
	private SimpleClient ggClient;

	private CSMessageInitializer csMsgInitializer;
	private SimpleCSNettyInitializer csInitializer;
	private SimpleServer cgServer;

	private HashMap<Integer, SimpleClient> gbClients;

	public void init() throws Exception
	{
		ssMsgInitializer = new SSMessageInitializer("com.game.gateway.action");
		ssMsgInitializer.initialize();
		ssInitializer = new SimpleSSNettyInitializer(ssMsgInitializer);
		ggClient = new SimpleClient();
		ggClient.initialize(ssInitializer, ssMsgInitializer);

		csMsgInitializer = new CSMessageInitializer("com.game.gateway.action");
		csMsgInitializer.initialize();
		csInitializer = new SimpleCSNettyInitializer(csMsgInitializer);
		cgServer = new SimpleServer();
		cgServer.initialize(csInitializer, csMsgInitializer);

		gbClients = new HashMap<Integer, SimpleClient>();

		Transmitter.getInstance().setMessageInitializer(ssMsgInitializer);
	}

	public void connectToGame()
	{
		ServerService service = ServiceContainer.getInstance().getPublicService(ServerService.class);
		BaseServerConfig config = service.getServerConfig();
		ggClient.connectTo(config.getManageServerAddress(), 5);
	}

	public void connectToBattles()
	{
		ServerService service = ServiceContainer.getInstance().getPublicService(ServerService.class);
		for (BattleInfoPROTO battle : service.getBattles())
		{
			if(gbClients.containsKey(battle.getServerID()))
				continue;
			
			SimpleClient gbClient = new SimpleClient();
			gbClient.initialize(ssInitializer, ssMsgInitializer);
			gbClient.connectTo(new InetSocketAddress(battle.getIpForServer(), battle.getPortForServer()), 1);
			gbClients.put(battle.getServerID(), gbClient);
		}
	}
	
	public void reconnectToServer(int serverID)
	{
		ServerService service = ServiceContainer.getInstance().getPublicService(ServerService.class);
		// Gateway 连接多个server的情况，game的节点只有一个，没有设置serverID，battle节点有多个，有设置serverId。
		if(serverID == 0)
		{
			BaseServerConfig config = service.getServerConfig();
			// gateway重连game服务器，清楚当前的session。
			SessionService sessionService = ServiceContainer.getInstance().getPublicService(SessionService.class);
			if(sessionService != null)
				sessionService.clearSession();
			// 关闭开放给客户端的端口
			cgServer.closePort(new InetSocketAddress(config.getPort4Client()));
			// 重新连接game服务器
			ggClient.connectTo(config.getManageServerAddress(), 5, true);
		}
		else if(gbClients.containsKey(serverID))
		{
			for (BattleInfoPROTO battle : service.getBattles())
			{
				if(battle.getServerID() == serverID)
				{
					gbClients.get(serverID).connectTo(new InetSocketAddress(battle.getIpForServer(), battle.getPortForServer()), 1, true);
					break;
				}
			}
		}
			
	}

	public void openPort4Client(int port)
	{
		boolean ret = cgServer.openPort(new InetSocketAddress(port));
		if (ret == false) {
			logger.error("Open Port Filed!",port);
		}
		logger.info("Begin to open port:{} for client", port);
	}
}
